package com.hw.one.collect.spadata.job;

import com.hw.one.collect.spadata.po.MissData;
import com.hw.one.collect.spadata.po.SpaPo;
import com.hw.one.collect.util.SerializeUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/23.
 */
@Component
public class SpaMissDataJob extends SpaDataJob {

    private static Logger log = Logger.getLogger(SpaMissDataJob.class);


    public void start() {
        try {
            log.info("----------开始查询SPA遗漏数据-----------------");
            // 获取异常数据
            List<Serializable> missList = getMissData();
            if (missList != null && missList.size() > 0) {
                log.info("----------查询到SPA遗漏数据" + missList.size() + "条-------------");
                // 有异常数据
                for (Serializable missDataSer : missList) {
                    // 反序列化
                    Object missDataObj = SerializeUtil.unSerialize((byte[]) missDataSer);
                    // 转换成 封装实体类
                    if (missDataObj instanceof MissData) {
                        MissData missData = (MissData) missDataObj;
                        int count = missData.getCount();
                        String searchTime = missData.getMONITORTIME();
                        // 处理之前，先把之前的数据删除
                        removeMissData(missDataSer);
                        // 如果查询次数大于三次，跳过不再拉取
                        if (count>3) {
                            log.info("------------拉取SPA遗漏数据大于三次，不再拉取【"+searchTime+"】--------------");
                            continue;
                        }
                        Map<String, String> paramMap = new HashMap<>();
                        paramMap.put("beginTime", searchTime);
                        paramMap.put("endTime", searchTime);
                        log.info("-----------拉取SPA遗漏数据----------");
                        List<SpaPo> spaPoList = execute(paramMap);

                        // 处理数据
                        if (null != spaPoList && spaPoList.size() == 1) {
                            log.info("-----------拉取成功，保存【"+searchTime+"】---------------");
                            // 刚好是一条
                            SpaPo spaPo = spaPoList.get(0);
                            saveSpaData(spaPo);
                        }else {
                            log.info("---------------本次拉取失败，保存到缓存-----------------");
                            // 未查询到数据，保存到异常数据
                            missData.setCount(++count);
                            saveMissData(missData);
                        }
                    }
                }
            }else {
                log.info("----------未查询到SPA遗漏数据-------------");
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("-----------拉取SPA遗漏数据时异常----------",e);
        }
    }
}
